package cool.xiaokang.familyaccount.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cool.xiaokang.familyaccount.dao.ManagerDao;
import cool.xiaokang.familyaccount.dao.RoleDao;
import cool.xiaokang.familyaccount.pojo.Manager;
import cool.xiaokang.familyaccount.pojo.Role;
import cool.xiaokang.familyaccount.service.ManagerService;
import cool.xiaokang.familyaccount.utils.CryptographyUtil;
import cool.xiaokang.familyaccount.utils.PageBean;

@Service
@Transactional
public class ManagerServiceImpl implements ManagerService {
	private static final Logger LOGGER = Logger.getRootLogger();
	@Autowired
	private ManagerDao managerDao;
	@Autowired
	private RoleDao roleDao;

	// 根据名称查询管理员
	@Override
	public Manager findManagerByName(String manager_name) {
		return managerDao.findManagerByName(manager_name);
	}

	@Override
	public void save(Manager manager, String[] roleIds) {
		if (StringUtils.isBlank(manager.getManager_pwd())) {
			manager.setManager_pwd("123456");
		}
		String pwd = CryptographyUtil.md5(manager.getManager_pwd(),
				CryptographyUtil.md5(CryptographyUtil.FAMILY, "familyaccount"));
		manager.setManager_pwd(pwd);
		if (roleIds != null && roleIds.length > 0) {
			for (String role_id : roleIds) {
				LOGGER.info("【ManagerServiceImpl-save】>>>role_id:" + role_id);
				System.out.println();
				Role role = roleDao.findById(role_id);
				manager.getRoles().add(role);
			}
		}
		managerDao.saveOrUpdate(manager);
	}

	// 查询数据
	public void pageQuery(PageBean pb) {
		managerDao.pageQuery(pb);
	}

	@Override
	public Manager findById(String manager_id) {
		return managerDao.load(manager_id);
	}

	// 修改信息
	public void update(Manager manager, String[] roleIds) {
		if (StringUtils.isBlank(manager.getManager_pwd())) {
			manager.setManager_pwd("123456");
		}
		String pwd = CryptographyUtil.md5(manager.getManager_pwd(),
				CryptographyUtil.md5(CryptographyUtil.FAMILY, "familyaccount"));
		manager.setManager_pwd(pwd);
		if (roleIds != null && roleIds.length > 0) {
			for (String role_id : roleIds) {  
				LOGGER.info("【ManagerServiceImpl-update】>>>role_id:" + role_id);
				Role role = roleDao.findById(role_id); 
				manager.getRoles().add(role);
			}
		}
		managerDao.update(manager);
	}

	// 修改密码
	public void editpwd(String manager_pwd, String manager_id) {
		manager_pwd = CryptographyUtil.md5(manager_pwd, CryptographyUtil.md5(CryptographyUtil.FAMILY, "familyaccount"));
		managerDao.executeUpdate("manager.initpwd", manager_pwd, manager_id);
	}

}
